package test.h0820;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Subsets {
    public static void main(String[] args) {
        int[] nums = {1, 2, 3,2};
        List<List<Integer>> subsets = generateSubsets(nums);
        for (List<Integer> subset : subsets) {
            System.out.println(subset);
        }
    }

    public static List<List<Integer>> generateSubsets(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        Arrays.sort(nums);
        backtrack(nums, result, new ArrayList<>(), 0);
        return result;
    }

    private static void backtrack(int[] nums, List<List<Integer>> result, List<Integer> tempList, int start) {
        result.add(new ArrayList<>(tempList)); // 添加当前子集到结果集中
        for (int i = start; i < nums.length; i++) {
            if (i>0&&nums[i]==nums[i-1]) continue;
            tempList.add(nums[i]); // 添加元素到当前子集
            backtrack(nums, result, tempList, i + 1); // 递归调用，i + 1 是为了避免重复使用元素
            tempList.remove(tempList.size() - 1); // 移除最后一个元素，进行回溯
        }
    }
}
